//-----------------------------------------------------
// nebulaApplication.cpp
//-----------------------------------------------------

/**
 * comment here
 */

#include "nebulaApplication.h"

#include <assert.h>

#include "kernel/nkernelserver.h"
#include "kernel/nfileserver2.h"
#include "resource/nresourceserver.h"
#include "gfx2/ngfxserver2.h"

namespace application {

	// Declare packages
	nNebulaUsePackage(nnebula);
	nNebulaUsePackage(ndirect3d9);

	CNebulaApplication::CNebulaApplication() {}
	CNebulaApplication::~CNebulaApplication() {}

	bool CNebulaApplication::init()
	{
		if(!CApplication::init())
			return false;

		initNebula();

		return true;
	}

	void CNebulaApplication::end()
	{
		CApplication::end();
		endNebula();
	}

	bool CNebulaApplication::initNebula()
	{
		kernelServer = new nKernelServer;

		// All packages have to be declared and added before you use them
		kernelServer->AddPackage(nnebula);
		kernelServer->AddPackage(ndirect3d9);

		this->refResourceServer = (nResourceServer*) kernelServer->New("nresourceserver", "/sys/servers/resource");
		this->refGfxServer = (nGfxServer2*) kernelServer->New("nd3d9server", "/sys/servers/gfx");

		// set shaders assign, needed for the gfx server,
		// this means that "shaders:" can be used to refer to the given directory.
		kernelServer->GetFileServer()->SetAssign("shaders", "home:data/shaders/fixed");

		nDisplayMode2 DisplayMode("Engine", nDisplayMode2::Windowed, 0, 0, 640, 480, false);
		refGfxServer->SetDisplayMode(DisplayMode);
		refGfxServer->SetCamera(gfxCamera);
		    
		bool result;
		result = refGfxServer->OpenDisplay();
		assert(result && "Error creating nebula display");
		 
		// to avoid dereferencing the nRef all the time
		// get a pointer to the gfx server. 
		gfxServer = refGfxServer.get();

		return true;
	}

	void CNebulaApplication::endNebula()
	{
		refGfxServer->CloseDisplay();

		refGfxServer->Release();
		refResourceServer->Release();

		delete kernelServer;
	}

	void CNebulaApplication::run()
	{
		// trigger the gfx server once every frame
		// Trigger() returns false if you close the window
		while (gfxServer->Trigger())
		{
			gfxServer->BeginScene();
			gfxServer->Clear(nGfxServer2::AllBuffers, 0.0f, 0.8f, 0.6f, 0.4f, 0.0f, 0);

			gfxServer->EndScene();
			gfxServer->PresentScene();

			// allow Windows to multitask
			n_sleep(0.0);
		}
	}

} // namespace application